package com.yipin.neimeng.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtil {
        static Logger logger = LoggerFactory.getLogger(AESUtil.class);
    // AES 加密方法
    public static String encrypt(String plainText, String key) throws Exception {
        // 将密钥和向量转换为字节数组
        byte[] keyBytes = key.getBytes("UTF-8");
        byte[] ivBytes = "0000000000000000".getBytes("UTF-8");

        // 创建密钥和初始化向量参数
        SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

        // 创建加密器，使用 AES/CBC/PKCS5Padding
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);

        // 执行加密操作
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));

        // 将加密后的字节数组转换为 Base64 编码的字符串
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }
    // AES 解密方法
    public static String decrypt(String encryptedText, String key) throws Exception {
        // 将密钥和向量转换为字节数组
        byte[] keyBytes = key.getBytes("UTF-8");
        byte[] ivBytes = "0000000000000000".getBytes("UTF-8");

        // 创建密钥和初始化向量参数
        SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

        // 创建解密器，使用 AES/CBC/PKCS5Padding
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);

        // 将 Base64 编码的加密文本解码为字节数组
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);

        // 执行解密操作
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        // 将解密后的字节数组转换为字符串
        return new String(decryptedBytes, "UTF-8");
    }
}
